var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');

var qiniu = require('qiniu');

var index = require('./routes/index');
var users = require('./routes/users');

var app = express();

var router = express.Router();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

let renderIndex = (req, res) => {
  res.sendFile(path.resolve(__dirname, './views/index.html'));
}
let imgUpdown = (req, res) => {

  //七牛
  var accessKey = 'zKaJ76-Kpm8cm_KdOEi74MA5z61qS2qKXZIOoMOh';
  var secretKey = 'v4aKVhbT9aVTQrNVAiIVL3O6VvJFX9WnogMJwiKf';
  var mac = new qiniu.auth.digest.Mac(accessKey, secretKey);

  var options = {
    scope: 'images',
  };
  var putPolicy = new qiniu.rs.PutPolicy(options);
  var uploadToken = putPolicy.uploadToken(mac);

  // console.log(req.body);

  var config = new qiniu.conf.Config();
  // 空间对应的机房
  config.zone = qiniu.zone.Zone_z0;

  // var localFile = "/Users/zhangze/Desktop/GIT/website/zhanggongze/调研/qiniu/public/images/index.jpg";
  // var formUploader = new qiniu.form_up.FormUploader(config);
  // var putExtra = new qiniu.form_up.PutExtra();
  // var key='test.jpg';
  // // 文件上传
  // formUploader.putFile(uploadToken, key, localFile, putExtra, function(respErr,
  //   respBody, respInfo) {
  //   if (respErr) {
  //     throw respErr;
  //   }
  //   if (respInfo.statusCode == 200) {
  //     console.log(respBody);
  //   } else {
  //     console.log(respInfo.statusCode);
  //     console.log(respBody);
  //   }
  // });

  var bucketManager = new qiniu.rs.BucketManager(mac, config);
  // var publicBucketDomain = 'http://oxcnsn9hv.bkt.clouddn.com';
  // // 公开空间访问链接
  // var publicDownloadUrl = bucketManager.publicDownloadUrl(publicBucketDomain, key);
  // console.log(publicDownloadUrl);

  var bucket = 'images';
  // @param options 列举操作的可选参数
  //                prefix    列举的文件前缀
  //                marker    上一次列举返回的位置标记，作为本次列举的起点信息
  //                limit     每次返回的最大列举文件数量
  //                delimiter 指定目录分隔符
  var options = {
    limit: 10,
    prefix: '',
  };
  bucketManager.listPrefix(bucket, options, function(err, respBody, respInfo) {
    if (err) {
      console.log(err);
      throw err;
    }
    if (respInfo.statusCode == 200) {
      //如果这个nextMarker不为空，那么还有未列举完毕的文件列表，下次调用listPrefix的时候，
      //指定options里面的marker为这个值
      var nextMarker = respBody.marker;
      var commonPrefixes = respBody.commonPrefixes;
      console.log(nextMarker);
      console.log(commonPrefixes);
      var items = respBody.items;
      items.forEach(function(item) {
        console.log(item.key);
        // console.log(item.putTime);
        // console.log(item.hash);
        // console.log(item.fsize);
        // console.log(item.mimeType);
        // console.log(item.endUser);
        // console.log(item.type);
      });
    } else {
      console.log(respInfo.statusCode);
      console.log(respBody);
    }
  });

  res.send({ 'success': "success" });
}

app.post('/imgUpdown', imgUpdown);
app.use('/', renderIndex);

// catch 404 and forward to error handler
app.use(function (req, res, next) {
  var err = new Error('Not Found');
  err.status = 404;
  next(err);
});

// error handler
app.use(function (err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

module.exports = app;
